<script setup>
import { Motion } from "motion-v";
import { computed, ref, onMounted, useTemplateRef } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useSearchStore } from "@/store/useSearchStore";
import { storeToRefs } from "pinia";

const router = useRouter();
const route = useRoute();

const query = ref(route.query.q ?? "");

const inputRef = useTemplateRef("input-ref");

const showButton = computed(() => {
  return route.name === "search";
});

const store = useSearchStore();
const { fromPage } = storeToRefs(store);
const { closeSearch } = store;

onMounted(() => {
  inputRef.value.focus();
});

const goToRoute = () => {
  if (query.value) {
    router.push({
      name: "search",
      query: { q: query.value },
    });
  } else {
    router.push({
      name: fromPage,
    });
  }
};

const goBack = () => {
  query.value = "";
  router.push({
    name: fromPage,
  });
};

const unFocus = (e) => {
  if (route.name !== "search") {
    const target = e.relatedTarget;
    if (!target || !target.classList.contains("search-toggle")) {
      query.value = "";
      closeSearch();
    }
  }
};
</script>

<template>
  <Motion
    as="div"
    :initial="{
      transform: 'translateY(-100%)',
    }"
    :animate="{
      transform: 'translateY(0)',
    }"
    :exit="{
      transform: 'translateY(-100%)',
    }"
    :transition="{
      duration: 0.2,
    }"
    class="fixed top-0 right-0 left-0 z-10 xl:left-[100px]"
  >
    <form autocomplete="off" @submit.prevent>
      <label
        class="absolute h-[1px] w-[1px] m-[-1px] overflow-hidden border-none [clip:rect(0,0,0,0)]"
        for="search"
        >Search</label
      >

      <div class="flex bg-secondary">
        <input
          id="search"
          ref="input-ref"
          v-model.trim="query"
          name="search"
          type="text"
          class="flex-1 h-[60px] p-[21px_15px] text-[16px] text-white xl:h-[80px] xl:p-[31px_50px] bg-transparent border-0 outline-0"
          placeholder="Search for a movie, tv show or person..."
          @keyup="goToRoute"
          @blur="unFocus"
        />

        <button
          v-if="showButton"
          class="flex items-center px-[15px] xl:px-[50px]"
          type="button"
          aria-label="Close"
          @click="goBack"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="15"
            height="15"
            viewBox="0 0 15 15"
          >
            <g
              fill="none"
              stroke="#fff"
              stroke-linecap="round"
              stroke-miterlimit="10"
              stroke-width="1.5"
            >
              <path d="M.75.75l13.5 13.5M14.25.75L.75 14.25" />
            </g>
          </svg>
        </button>
      </div>
    </form>
  </Motion>
</template>
